import { useLocation, useNavigate, useRoutes } from "react-router-dom";
import { useState, useEffect } from "react";
import storage from "@/utils/storage";

const BeforeEnter = ({ routers }) => {
  //1.在路由数组中找当前页面路由的对应路由项
  const fineRouter = (routes, path) => {
    for (const val of routes) {
      if (val.path === path) return val;
      if (val.children) {
        const name = fineRouter(val.children, path);
        if (name) {
          return name;
        }
      }
    }
  };

  //2.路由守卫判断
  const judgeRouter = (location, navigate) => {
    const { pathname } = location;
    //2.1路由数组找路由项
    const findRoute = fineRouter(routers, pathname);
    console.log(findRoute);
    //2.2没找到，说明没有这个路由，直接404
    if (!findRoute) {
      navigate("/404");
      return;
    }
    const toekn = storage.getItem("like_admin_token");
    console.log(toekn);
    // if (!toekn && findRoute.path != "/login") {
    //   navigate("/login");
    // }
    if (findRoute.mete) {
      document.title = findRoute.mete.title;
    }
  };

  //3.基于useEffect监听页面路由改变。然后组件重新加载，又重新校验权限。
  const navigate = useNavigate();
  const location = useLocation();
  const router = useRoutes(routers);
  useEffect(() => {
    //路由守卫判断
    judgeRouter(location, navigate);
  }, [navigate, location]);
  return router;
};
export default BeforeEnter;
